/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2019年4月6日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.lesson3.tree.binarytree;

/**
 * @Type TreeNode
 * @Desc
 * @author 52489
 * @date 2019年4月6日
 * @Version V1.0
 */
public class TreeNode {
    // 节点的权
    int value;

    TreeNode leftNode;
    TreeNode rightNode;

    public void setLeftNode(TreeNode leftNode) {
        this.leftNode = leftNode;
    }

    public void setRightNode(TreeNode rightNode) {
        this.rightNode = rightNode;
    }

    /**
     * 
     */
    public TreeNode(int value) {
        this.value = value;
    }

    /**
     * 前序遍历
     */
    public void frontShow() {
        System.out.println(value);
        if (leftNode != null) {
            leftNode.frontShow();
        }

        if (rightNode != null) {
            rightNode.frontShow();

        }
    }

    // 后序遍历
    public void midShow() {
        if (leftNode != null) {
            leftNode.midShow();
        }

        System.out.println(value);

        if (rightNode != null) {

            rightNode.midShow();

        }
    }

    public void afterShow() {
        if (leftNode != null) {
            leftNode.afterShow();
        }

        if (rightNode != null) {
            rightNode.afterShow();
        }
        System.out.println(value);
    }

    /**
     * @return
     */
    public TreeNode frontSearch(int searchValue) {
        TreeNode target = null;
        if (searchValue == value) {
            target = this;
        } else {

            if (leftNode != null) {
                target = leftNode.frontSearch(searchValue);
            }

            if (rightNode != null) {
                target = rightNode.frontSearch(searchValue);

            }
        }

        return target;
    }

    /**
     * @param i
     */
    public void delete(int i) {
        TreeNode parent = this;
        // 判断是否是左儿子
        if (null != parent.leftNode && parent.leftNode.value == i) {
            parent.leftNode = null;
        }
        // 判断是否是右儿子

        if (null != parent.rightNode && parent.rightNode.value == i) {
            parent.rightNode = null;
        }

        parent = leftNode;
        // 递归删除左儿子
        if (parent != null) {
            parent.delete(i);
        }

        parent = rightNode;
        // 递归删除右儿子

        if (parent != null) {
            parent.delete(i);
        }
    }
}
